package alipay

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"log"
	"net/url"
	"strconv"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/pkg/authorized"
	"yundian/internel/app/models/coupon"
	"yundian/internel/app/models/couponinfo"
	"yundian/internel/pkg/dingo"
	. "yundian/internel/pkg/dingo/result"
)

type RoomVendingConfirmRes struct {
	AppId     string `json:"appId"`
	Code      string `json:"code"`
	Nonce     string `json:"nonce"`
	Timestamp string `json:"timestamp"`
	Sign      string `json:"sign"`
}

//携程对接接口
func RoomVendingConfirm(ctx *gin.Context) {
	param := &struct {
		Code string `json:"code"`
	}{}

	resParam := &struct {
		Status        int    `json:"status"`
		Discounts     int    `json:"discounts"`
		RetCode       int    `json:"retCode"`
		Message       string `json:"message"`
		ReceiveStatus int    `json:"receiveStatus"`
		CanFree       bool   `json:"canFree"`
		FirstRemark   string `json:"firstRemark"`
	}{}

	dingo.ErrorIf(ctx.Bind(param)).Unwrap()
	////从token中获取userId
	userId, err := helper.GetUserIdFromCtx(ctx)
	if userId == 0 {
		log.Println("获取userId：", userId)
		Response(ctx)("无效的token", CodeError, resParam)(OK)
		return
	}

	//从token中获取OpenId
	openid, err := helper.GetUserNameFromCtx(ctx)
	if openid == "" {
		log.Println("获取openId：", openid)
		Response(ctx)("无效的token", CodeError, resParam)(OK)
		return
	}
	//userId := 6
	//openid := "oH48946_DLiOQu9YH4a-9yB-9FGQ"
	//.Unwrap().(*couponinfo.CouponInfo)
	getCouponInfo, getRowsAffected := dao.NewCouponDao().GetCouponInfoStatus(openid)
	discounts := getCouponInfo.Unwrap().(int)
	if getRowsAffected > 0 {
		resCouponInfoParam := &struct {
			Discounts     int    `json:"discounts"`
			ReceiveStatus int    `json:"receiveStatus"`
			FirstRemark   string `json:"firstRemark"`
		}{}
		resCouponInfoParam.ReceiveStatus = 1
		resCouponInfoParam.Discounts = discounts
		resCouponInfoParam.FirstRemark = "您有一张未使用的携程用户专享充电福利～"
		Response(ctx)("存在未使用优惠券", CodeSuccess, resCouponInfoParam)(OK)
		return
	}

	//请求参数
	responseModel := &RoomVendingConfirmRes{}

	responseModel.AppId = "1000228640002"
	responseModel.Code = param.Code
	responseModel.Nonce = authorized.GetRandomString(32)
	responseModel.Timestamp = strconv.FormatInt(time.Now().UnixNano(), 10)
	responseModel.Sign = url.QueryEscape("appId=" + responseModel.AppId + "&code=" + responseModel.Code + "&nonce=" + responseModel.Nonce + "&timestamp=" + responseModel.Timestamp)

	//签名加密
	appSecret := "c830488c774a122844c78fc09b075792"
	s := []byte(responseModel.Sign)
	key := []byte(appSecret)
	m := hmac.New(sha256.New, key)
	m.Write(s)
	signature := hex.EncodeToString(m.Sum(nil))
	//签名
	responseModel.Sign = signature

	payload, _ := json.Marshal(responseModel)

	urlStr := "https://apiproxy.ctrip.com/apiproxy/soa2/18518/roomVendingConfirm"
	respMap, err := authorized.PostRequest(urlStr, map[string]string{"Content-Type": "application/json"}, bytes.NewReader(payload))
	if err != nil {
		resParam.Status = 2 //无效Code
		log.Println("携程code是否可用：", respMap["canFree"])
		Response(ctx)("无效的code", CodeError, resParam)(OK)
		return
	}
	//绑定返回参数
	respMapByte, _ := json.Marshal(respMap)
	_ = json.Unmarshal(respMapByte, &resParam)
	log.Println("携程返回信息:---------", resParam, "携程code:--------", param.Code)

	////判断是否存在多张优惠券
	//_, rowsAffected := dao.NewCouponDao().GetCouponInfo(userId)
	////已存在多张优惠券
	//if rowsAffected > 0 {
	//
	//	//couponInfoModel := isCouponInfo.Unwrap().(*couponinfo.CouponInfo)
	//	couponData := dao.NewCouponDao().GetCoupon(1).Unwrap().(*coupon.Coupon)
	//
	//	resParam.Status = 2
	//	resParam.Discounts = couponData.Discounts
	//	log.Println("已存在优惠券：")
	//	Response(ctx)("已存在优惠券", CodeError, resParam)(Error)
	//	return
	//}

	//查询最新的一条优惠券
	//couponInfoLimit := dao.NewCouponDao().GetCouponInfoLimit(userId).Unwrap().(*couponinfo.CouponInfo)
	//
	////判断是否在一年内
	//fmt.Println(time.Now().Unix(), int64(couponInfoLimit.StartTime))
	//if time.Now().Unix()-int64(couponInfoLimit.StartTime) > 3600*24*365 {
	//	fmt.Println("你好一年内不得再次领取")
	//	log.Println("一年内不得再次领取：", respMap["canFree"])
	//	resParam.Status = 2
	//	Response(ctx)("无效的code", CodeError, resParam)(OK)
	//	return
	//}

	//通过携程接口 领取优惠券
	if resParam.ReceiveStatus == 1 {

		//判断是否存在多张优惠券
		_, rowsAffected := dao.NewCouponDao().GetCouponInfo(userId)
		//已存在多张优惠券
		if rowsAffected > 0 {

			//couponInfoModel := isCouponInfo.Unwrap().(*couponinfo.CouponInfo)
			couponData := dao.NewCouponDao().GetCoupon(1).Unwrap().(*coupon.Coupon)

			resParam.Status = 2
			resParam.Discounts = couponData.Discounts
			log.Println("已存在优惠券：", resParam)
			Response(ctx)("已存在优惠券", CodeError, resParam)(Error)
			return
		}

		//扩展 需要传优惠券Id 以便领取对应的优惠券
		couponInfoModel := dao.NewCouponDao().GetCoupon(1).Unwrap().(*coupon.Coupon)
		couponInfo := couponinfo.New()
		couponInfo.UserId = userId
		couponInfo.CId = 1
		couponInfo.StartTime = int(time.Now().Unix())
		couponInfo.Discounts = couponInfoModel.Discounts
		couponInfo.OpenId = openid
		couponInfo.Status = 1

		//		couponInfoModel := dao.NewCouponDao().GetCouponByIdx("xc").Unwrap().(*coupon.Coupon)
		//		couponInfo := couponinfo.New()
		//		couponInfo.UserId = userId
		//		couponInfo.CId = couponInfoModel.Id
		//		couponInfo.StartTime = int(time.Now().Unix())
		//		couponInfo.Discounts = couponInfoModel.Discounts
		//		couponInfo.OpenId = openid
		//		couponInfo.Status = 1

		//添加优惠券
		dao.NewCouponDao().InsertCouponInfo(couponInfo)

		//resParam.FirstRemark = utils.Join(resParam.FirstRemark, " ", strconv.Itoa(couponInfoModel.Discounts), "元")
		resParam.Status = 1
		resParam.Discounts = couponInfoModel.Discounts
		//优惠券领取后需要对发放数量减一操作 todo
		//couponModel := coupon.New()
		log.Println("优惠券领取成功：", resParam, openid)
		Response(ctx)("优惠券领取成功", CodeSuccess, resParam)(OK)

	} else {
		resParam.Status = 2 //无效Code
		log.Println("携程code是否可用：", respMap["canFree"], resParam)
		Response(ctx)("无效的code", CodeError, resParam)(Error)
	}

}
